package com.cash.app.ui.start

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.cash.app.R
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import com.cash.app.base.BaseActivity
import com.cash.app.constant.AppConstant
import com.cash.app.constant.AppConstant.SPLASH_JUMP_TIME
import com.cash.app.databinding.AcSplashBinding
import com.cash.app.ui.main.MainActivity
import com.cash.app.utils.SpUtils

@SuppressLint("CustomSplashScreen")
class SplashActivity : BaseActivity() {

    private lateinit var binding: AcSplashBinding

    override val statusBarColor: Int
        get() = R.color.transparent

    override val isFitsSystemWindows: Boolean
        get() = false

    override fun setViewBind() {
        binding = AcSplashBinding.inflate(layoutInflater)
    }

    override fun getLayoutView(): View {
        return binding.root
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        startTimer()
    }

    private fun startTimer() {
        // Use lifecycleScope for delayed navigation
        lifecycleScope.launch {
            try {
                delay(SPLASH_JUMP_TIME)
                if (!isFinishing) {
                    jumpToPage()
                }
            } catch (e: Exception) {
                e.printStackTrace()
                if (!isFinishing) {
                    jumpToPage()
                }
            }
        }
    }

    private fun jumpToPage() {
        if (SpUtils.get(AppConstant.K_PP_GRANTED, false)) {
            startActivity(Intent(this@SplashActivity, MainActivity::class.java))
            finish()
        } else {
            startActivity(Intent(this@SplashActivity, PolicyActivity::class.java))
            finish()
        }
    }
}